package com.lsj.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lsj.core.page.QueryPage;
import com.lsj.core.page.ResultPage;
import com.lsj.core.response.CommonResult;
import com.lsj.core.validate.Add;
import com.lsj.core.validate.Update;
import com.lsj.dto.sys.UserDto;
import com.lsj.dto.sys.UserPwdResetDto;
import com.lsj.dto.sys.UserUpdateDto;
import com.lsj.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author:lin.sj
 * @Data:2021/7/7 19:45
 * @Desc: 用户信息处理器
 */
@RestController
@RequestMapping("/sys_user")
@Api(tags = "用户处理")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public CommonResult register(@RequestBody @Validated(value = Add.class) UserDto userDto){
        userService.register(userDto);
        return CommonResult.success();
    }

    @GetMapping("/validateUsername")
    @ApiOperation(value = "验证用户名是否存在")
    public CommonResult validateUsername(String username){
        if(StringUtils.isBlank(username)){
            return CommonResult.error("账户不能为空");
        }
        boolean exists = userService.validateUsername(username);
        return CommonResult.success(exists);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public CommonResult updateUser(@RequestBody @Validated(value = Update.class) UserUpdateDto userUpdateDto){
        userService.updateUser(userUpdateDto);
        return CommonResult.success();
    }

    @PostMapping("/list")
    @ApiOperation(value = "获取用户列表")
    public CommonResult listUser(@RequestBody QueryPage<UserDto> queryPage){
        ResultPage<UserDto> userPage = userService.listUser(queryPage);
        return CommonResult.success(userPage);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    public CommonResult deleteUser(@RequestBody Map param){
        Long userId = Convert.toLong(param.get("userId"));
        userService.deleteUserById(userId);
        return  CommonResult.success();
    }

    @PostMapping("/passwordReset")
    @ApiOperation(value = "密码重置")
    public CommonResult passwordReset(@RequestBody @Validated(Update.class)UserPwdResetDto resetDto){
        userService.passwordReset(resetDto);
        return CommonResult.success();
    }

}
